package o2o.config.exception;

import com.alibaba.fastjson.JSONObject;
import com.jinyou.utils.common.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import o2o.utils.resp.EResultCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Jahnke【1029777564@qq.com】
 * @ClassName JyExceptionAdvice
 * @Description:
 * @date 2019/11/18 11:14
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class JyExceptionAdvice {


    // todo: 空指针异常
    @ExceptionHandler(value = NullPointerException.class)
    public String handleNullException(NullPointerException e) {
        log.error("系统空指针异常:", e);
        return AjaxResult.errorResult("资源未找到");
    }

    // todo: 自定义异常
    @ExceptionHandler(value = JyResultException.class)
    public String handleResultException(JyResultException e) {
        log.error("系统业务异常~原因是:{}", e.getMessage());
        return e.getCode() != null && e.getCode().equals(String.valueOf(EResultCode.NOT_LOGIN.getCode())) ? AjaxResult.errorLogoutResult() : errorResult(e.getMessage(), e.getCode(), e.getType());
    }

    // todo: 其他异常
    @ExceptionHandler(value = Exception.class)
    public String handleException(Exception e) {
        log.error("系统业务异常~原因是:{}", e.getMessage());
        return AjaxResult.errorResult(e.getMessage());
    }

    // todo: 回写
    private static String errorResult(String error, String code, String type) {
        JSONObject result = new JSONObject();
        result.put("status", 0);
        if (StringUtils.isNotEmpty(error)) {
            result.put("type", StringUtils.isEmpty(type) ? "comError" : type);
            result.put("error", error);
            // result.put("code", StringUtils.isEmpty(code) ? "200" : code);
        }
        return result.toString();
    }
}
